import WeCropper from '../../we-cropper/we-cropper.js'

const device = wx.getSystemInfoSync()
const width = device.windowWidth;
const height = (device.windowHeight - 50);
const defWidth = 350;
const defHeight = 350;
var cf = require("../../config.js");
const app = getApp()
Page({
  data: {
    app:app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.downLoadUploadPath,//new https
    saveKey:"headImg",
    isArrKey:false,
    relativeUrl:false,
    isLoading:false,
    cropperOpt: {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - defWidth) / 2,
        y: (height - defHeight) / 2,
        width: defWidth,
        height: defHeight
      }
    },
    uploadParams:{}
  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)
  },
  getCropperImage() {
    var ctx = this;
    if (ctx.data.isLoading){
      return;
    }
    ctx.setData({
      isLoading:true
    });
    this.wecropper.getCropperImage((avatar) => {
      if (avatar) {
        //  获取到裁剪后的图片
        // wx.redirectTo({
        //   url: `../index/index?avatar=${avatar}`
        // })
        this.uploadImg(avatar);
      } else {
        console.log('获取图片失败，请稍后重试')
      }
    })
  },
  uploadTap() {
    const self = this

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值
        self.wecropper.pushOrign(src)
      }
    })
  },
  
  uploadImg(tempFilePath,type='image',isSingle=false){
    if(tempFilePath.constructor==Array ){
      tempFilePath = tempFilePath[0]
    }
    var ctx = this;
    wx.showLoading({
      title: '上传中...',
    });
    let arr = tempFilePath.split('.')
    let formatFileName
    if(isSingle){
      formatFileName = wx.getStorageSync('userId')+'.'+arr[arr.length-1]
    } else {
      formatFileName = wx.getStorageSync('userId')+'/'+new Date().getTime()+'.'+arr[arr.length-1]
    }
    let newFileName = `/${type}/card/${formatFileName}`;
    const a = ctx.data.uploadParams
    let newFilePath =ctx.data.uploadParams.host +"/" + a.dir+newFileName;
    wx.uploadFile({
      url: ctx.data.uploadParams.host,
      name: 'file',
      filePath:tempFilePath,
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        OSSAccessKeyId:a.accessid,
        policy:a.policy,
        signature:a.signature,
        key: a.dir + newFileName,
        success_action_status: 200
      },
      success: function (res) {
        // debugger
        let pages = getCurrentPages()
        let prevPage = pages[pages.length - 2];//上一页面
        if(ctx.data.saveKey=='headImg'){
          prevPage.setData({//直接给上移页面赋值
            headImg: newFilePath
          });
        } else if(ctx.data.saveKey=='videoImg') {
          prevPage.setData({//直接给上移页面赋值
            videoImg: newFilePath
          });
        }else{
          prevPage.setData({//直接给上移页面赋值
            headImg: newFilePath,
            reload:true
          });
        }
        
        wx.navigateBack({
          delta: 1
        });
        wx.hideLoading();
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  aliyunUploadToken(){
    let that = this;
    wx.request({
      url:cf.config.pageDomain + '/applet/mobile/aliyunoss/getUploadToken',
      header:{
        "Content-Type": "application/json"
      },
      success:function(res){
        that.setData({
          uploadParams:res.data.model
        })
      }
    })
  },
  onLoad(option) {
    this.aliyunUploadToken()
    const { cropperOpt } = this.data;
    if (undefined != option.scaleXY) {
      cropperOpt.cut = {
        scale: 2.5,
        zoom: 8,
        x: (width - defWidth) / 2,
        y: (height - defHeight / option.scaleXY) / 2,
        width: defWidth,
        height: defHeight / option.scaleXY
      }
    }
    if (option.relative){//是否保存 相对路径  默认保存全路径
      this.setData({
        relativeUrl:true
      });
    }
   
    if (option.isArr){//是否保存的 key 是一个数组， 默认是一个字符串
      this.setData({
        isArrKey:true
      });
    }
    if (option.saveKey){//指定回填的key， 就行需要给上一个页面(data)的哪个Key赋值
      this.setData({
        saveKey: option.saveKey
      });
    }
    if (option.src) {
      cropperOpt.src = option.src
      new WeCropper(cropperOpt)
        .on('ready', (ctx) => {
          console.log(`wecropper is ready for work!`)
        })
        .on('beforeImageLoad', (ctx) => {
        })
        .on('imageLoad', (ctx) => {
        })
        .on('beforeDraw', (ctx, instance) => {
        })
        .updateCanvas()
    }
  }
})
